<!---@components: ToolMain: @/views/aitools/components/ToolMain/index.vue------>
<template>
  <div class="ai-tools-main flex w-full flex-col items-center gap-5">
    <!-- 搜索 -->
    <h3 class="mt-[50px] text-[32px]">AI工具箱</h3>
    <div class="search-box relative min-w-[400px] max-w-[600px] pt-[60px]">
      <!-- input-box 脱离文档流-->
      <div
        class="input-box absolute left-0 top-0 w-full transition-all duration-300"
        :class="{ 'is-focus': isFocus }"
        @click="isFocus = true"
      >
        <div class="flex">
          <span
            :class="[
              'flex h-12 w-12 items-center justify-center rounded-lg text-2xl font-bold text-white'
            ]"
          >
            ✨
          </span>
          <el-input
            v-model="keyword"
            clearable
            class="h-[52px] transition-all"
            placeholder="请输入搜索内容"
            @focus="isFocus = true"
            @blur="handleBlur"
          >
            <template #append>
              <el-button
                type="primary"
                class="!h-[52px] !rounded-l-none !text-[#FFFFFF]"
                :icon="Search"
                :style="{ 'background-color': isFocus ? '#409EFF' : '#000', 'font-size': '20px' }"
                @click.stop=""
              />
            </template>
          </el-input>
        </div>
        <!-- 推荐内容-->
        <div v-if="isFocus" class="recommend-panel px-4 py-3">
          <div class="mb-2 text-sm text-gray-500">{{ keyword ? '智能推荐' : '常用推荐' }}</div>
          <ul class="max-h-[150px] overflow-y-auto">
            <li
              v-for="(item, index) in filteredTools"
              :key="index"
              class="flex cursor-pointer items-center justify-between px-2 py-3 hover:bg-gray-100"
              @mousedown.prevent="selectTool(item)"
            >
              <!-- <span>{{ item.name }}</span> -->
              <span v-html="highlightKeyword(item.name)" />
              <el-icon><ArrowRightBold /></el-icon>
            </li>
          </ul>
          <div v-if="keyword && filteredTools.length === 0" class="py-4 text-center text-gray-400">
            暂无匹配的工具
          </div>
        </div>
      </div>

      <!-- 工具列表 -->
      <ul class="mt-4 flex px-2">
        <li
          v-for="(item, index) in tools"
          :key="index"
          class="mr-10 cursor-pointer last:mr-0"
          @click="openTool(item)"
        >
          {{ item.name }}
        </li>
      </ul>
    </div>
    <!-- 工具箱 -->
    <AiToolBox />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed, markRaw, watch } from 'vue'
  import { Search, ArrowRightBold } from '@element-plus/icons-vue'
  import { emitter } from '@/utils/mitt'
  import AiToolBox from '../AiToolBox/index.vue'
  import { Tools as toolData } from '../data.ts'
  import type { ToolItem } from '../data.ts'

  const keyword = ref('')
  const toolList = ref<ToolItem[]>(toolData)
  const tools = ref([])

  const isFocus = ref(false)

  const commonTool = ref([])

  const filteredTools = computed(() => {
    if (!keyword.value.trim()) {
      return commonTool.value // 无关键词时显示所有常用工具
    }

    const searchKeyword = keyword.value.trim().toLowerCase()
    return commonTool.value.filter(
      tool =>
        tool.name.toLowerCase().includes(searchKeyword) ||
        tool.description.toLowerCase().includes(searchKeyword)
    )
  })

  const highlightKeyword = (text: string) => {
    if (!keyword.value.trim()) {
      return text
    }

    const regex = new RegExp(`(${keyword.value.trim()})`, 'gi')
    return text.replace(regex, '<span class="bg-yellow-200 text-yellow-800">$1</span>')
  }

  const handleBlur = () => {
    // 延迟关闭，避免点击选项时立刻消失
    setTimeout(() => {
      isFocus.value = false
    }, 200)
  }

  const selectTool = (tool: ToolItem) => {
    keyword.value = tool.name
    isFocus.value = false
    openTool(tool)
  }

  const openTool = (tool: ToolItem) => {
    emitter.emit('openByTag', false)
    emitter.emit('openAiTool', { ...tool, tabKey: `${tool.key}-${Date.now()}` })
  }

  watch(keyword, newVal => {
    if (newVal) {
      commonTool.value = toolList.value
    }
  })

  onMounted(() => {
    let idList = [1, 4, 2, 12, 13]
    tools.value = toolList.value.filter(item => idList.includes(item.id))
    commonTool.value = toolList.value.filter(tool => tool.type.split(',').includes('common'))
  })
</script>

<style scoped lang="scss">
  :deep(.el-input__wrapper) {
    box-shadow: none !important; /* 去掉内置阴影边框 */
    border: none !important; /* 去掉边框 */
  }

  :deep(.el-input__wrapper.is-focus) {
    box-shadow: none !important;
    border: none !important;
  }
  :deep(.el-input-group__prepend) {
    background-color: transparent;
    width: 30px;
  }
  .input-box {
    height: 52px;
    border: 1px solid #000;
    border-radius: 8px;
    overflow: hidden;
    z-index: 1;
  }

  .input-box.is-focus {
    height: auto;
    max-height: 250px;
    border: 1px solid #409eff;
    box-shadow: 0 0 6px rgba(64, 158, 255, 0.3);
    z-index: 10; /* 确保在最上层 */
    background: #fff;
  }

  .recommend-panel {
    border-top: 1px solid #eee;
    li {
      .el-icon {
        color: #666; // 默认灰色
        transition: color 0.2s;
      }

      &:hover {
        background: #f5f5f5;

        .el-icon {
          color: #409eff; // 鼠标移入变蓝
        }
      }
    }
  }
</style>
